package com.platform.controller.shop;

import cn.hutool.core.lang.UUID;
import com.platform.dao.shop.GoodsDao;
import com.platform.entity.SysUserEntity;
import com.platform.entity.shop.GoodsEntity;
import com.platform.entity.shop.GoodsQrcodeEntity;
import com.platform.oss.CloudStorageService;
import com.platform.oss.OSSFactory;
import com.platform.service.SysConfigService;
import com.platform.service.shop.GoodsService;
import com.platform.utils.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.awt.image.BufferedImage;
import java.io.File;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Controller
 *
 * @author lipengjun
 * @email 939961241@qq.com
 * @date 2017-08-21 21:19:49
 */
@RestController
@RequestMapping("goods")
public class GoodsController {
    @Autowired
    private GoodsService goodsService;

    @Autowired
    private SysConfigService sysConfigService;

    /**
     * 查看列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("goods:list")
    public R list(@RequestParam Map<String, Object> params) {
        SysUserEntity sysUserEntity= ShiroUtils.getUserEntity();
        //查询列表数据
        Query query = new Query(params);
        query.put("merchantId",sysUserEntity.getMerchantId());
        query.put("isDelete", 0);
        query.put("sidx", "sort_order");
        query.put("order", "asc");
        List<GoodsEntity> goodsList = goodsService.queryList(query);
        int total = goodsService.queryTotal(query);

        PageUtils pageUtil = new PageUtils(goodsList, total, query.getLimit(), query.getPage());

        return R.ok().put("page", pageUtil);
    }

    /**
     * 查看信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("goods:info")
    public R info(@PathVariable("id") Integer id) {
        GoodsEntity goods = goodsService.queryObject(id);

        return R.ok().put("goods", goods);
    }

    @Autowired
    private GoodsDao goodsDao;

    /**
     * 防伪码生成
     */
    @RequestMapping("/createQrcode")
    public R createQrcode(@RequestParam("goodsId") Integer goodsId) {
        GoodsEntity goods = goodsService.queryObject(goodsId);

        if(goods == null){
            return R.error("商品goodsId:"+goodsId+"不存在");
        }

        Integer maxCodeCount = Integer.parseInt(sysConfigService.getValue("max_code_count", "2"));

        Integer minCodeCount = Integer.parseInt(sysConfigService.getValue("min_code_count", "60"));

        if(goodsId.equals(1) || goodsId.equals(6)){
            maxCodeCount = 500;
            minCodeCount = 60;
        }else{
            maxCodeCount = 167;
            minCodeCount = 60;
        }

        List<GoodsQrcodeEntity> goodsQrcodeEntityList = new ArrayList<>();

        CloudStorageService cloudStorageService = OSSFactory.build();
        String iscreate_qrcode_url = sysConfigService.getValue("iscreate_qrcode_url", "0");

        createQrcode(cloudStorageService, goodsId, maxCodeCount, minCodeCount, goodsQrcodeEntityList, iscreate_qrcode_url);

        goodsDao.batchSaveGoodsQrcode(goodsQrcodeEntityList);

        return R.ok("防伪码生成成功");
    }

    private void createQrcode(CloudStorageService cloudStorageService, Integer goodsId, Integer maxCodeCount, Integer minCodeCount, List<GoodsQrcodeEntity> goodsQrcodeEntityList, String iscreate_qrcode_url) {
        for(int i = 0; i < maxCodeCount; i++){
            String securityCode = "x-"+UUID.randomUUID().toString();
            GoodsQrcodeEntity goodsQrcodeEntity = new GoodsQrcodeEntity();
            goodsQrcodeEntity.setAddTime(new Date());
            goodsQrcodeEntity.setGoodsId(goodsId);
            goodsQrcodeEntity.setSecurityCode(securityCode);
            goodsQrcodeEntity.setScanCount(0);
            String content = "https://mp.jianguoes.com/shop/goods/mycode/goods_id/securitycode.html?securityCode="+securityCode;
            goodsQrcodeEntity.setSecurityCodeCtx(content);

            if("1".equals(iscreate_qrcode_url)){
                try{
                    BufferedImage qrcode = QRCodeUtil.createImage(content, null, true);
                    String qrCodeUrl = cloudStorageService.upload(QRCodeUtil.imageToBytes(qrcode), "securitycode/"+ goodsId + "/x/" + securityCode +".png");
                    goodsQrcodeEntity.setQrcodeUrl(qrCodeUrl);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            goodsQrcodeEntityList.add(goodsQrcodeEntity);

            for(int j = 0; j < minCodeCount; j++){
                String securityCode2 = "s-"+UUID.randomUUID().toString();
                GoodsQrcodeEntity goodsQrcodeEntity2 = new GoodsQrcodeEntity();
                goodsQrcodeEntity2.setAddTime(new Date());
                goodsQrcodeEntity2.setGoodsId(goodsId);
                goodsQrcodeEntity2.setSecurityCode(securityCode2);
                goodsQrcodeEntity2.setScanCount(0);
                String content2 = "https://mp.jianguoes.com/shop/goods/mycode/goods_id/securitycode.html?securityCode="+securityCode2;
                goodsQrcodeEntity2.setSecurityCodeCtx(content2);

                goodsQrcodeEntity2.setParentCode(goodsQrcodeEntity.getSecurityCode());

                goodsQrcodeEntity2.setSecurityCodeCtx(content2);
                goodsQrcodeEntity2.setParentCodeCtx(goodsQrcodeEntity.getSecurityCodeCtx());

                if("1".equals(iscreate_qrcode_url)){
                    try{
                        BufferedImage qrcode = QRCodeUtil.createImage(content2, null, true);
                        String qrCodeUrl = cloudStorageService.upload(QRCodeUtil.imageToBytes(qrcode), "securitycode/"+ goodsId + "/s/" + securityCode2 +".png");
                        goodsQrcodeEntity2.setQrcodeUrl(qrCodeUrl);
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
                goodsQrcodeEntityList.add(goodsQrcodeEntity2);
            }
        }
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("goods:save")
    public R save(@RequestBody GoodsEntity goods) {
        buildRelGoodsId(goods);
        SysUserEntity sysUserEntity= ShiroUtils.getUserEntity();
        goods.setMerchantId(sysUserEntity.getMerchantId());
        goodsService.save(goods);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("goods:update")
    public R update(@RequestBody GoodsEntity goods) {

        buildRelGoodsId(goods);

        goodsService.update(goods);

        return R.ok();
    }

    private void buildRelGoodsId(GoodsEntity goods) {
        if(StringUtils.isNotEmpty(goods.getRelGoodsId())){

            String[] goodsArr = goods.getRelGoodsId().split(";");
            if(goodsArr != null && goodsArr.length > 0){

                BigDecimal retailPrice = BigDecimal.ZERO;
                BigDecimal vipPrice = BigDecimal.ZERO;
                BigDecimal shopPrice = BigDecimal.ZERO;
                BigDecimal agentPrice = BigDecimal.ZERO;
                BigDecimal regionPrice = BigDecimal.ZERO;
                BigDecimal coopPrice = BigDecimal.ZERO;

                BigDecimal couponAmount = BigDecimal.ZERO;
                BigDecimal levelAmount = BigDecimal.ZERO;
                for(String rel : goodsArr){

                    String[] relInfo = rel.split(":");
                    if(relInfo != null && relInfo.length == 2){
                        GoodsEntity relGoods = goodsService.queryObject(Integer.parseInt(relInfo[0]));
                        if(relGoods != null){
                            retailPrice = retailPrice.add(relGoods.getRetailPrice().multiply(new BigDecimal(relInfo[1])));
                            vipPrice = vipPrice.add(relGoods.getVipPrice().multiply(new BigDecimal(relInfo[1])));
                            shopPrice = shopPrice.add(relGoods.getShopPrice().multiply(new BigDecimal(relInfo[1])));
                            agentPrice = agentPrice.add(relGoods.getAgentPrice().multiply(new BigDecimal(relInfo[1])));
                            regionPrice = regionPrice.add(relGoods.getRegionPrice().multiply(new BigDecimal(relInfo[1])));
                            coopPrice = coopPrice.add(relGoods.getCoopPrice().multiply(new BigDecimal(relInfo[1])));
                            couponAmount = couponAmount.add(relGoods.getCouponAmount().multiply(new BigDecimal(relInfo[1])));
                            levelAmount = levelAmount.add(relGoods.getLevelAmount().multiply(new BigDecimal(relInfo[1])));
                        }
                    }

                }
                // 套餐的游客价格设置为vip价格
                goods.setRetailPrice(vipPrice);
                goods.setVipPrice(vipPrice);
                if(goods.getIsSecKill().equals(5)){// 活动的商品统一为vip价格
                    goods.setShopPrice(vipPrice);
                    goods.setAgentPrice(vipPrice);
                    goods.setRegionPrice(vipPrice);
                    goods.setCoopPrice(vipPrice);
                    goods.setCouponAmount(BigDecimal.ZERO);
                    goods.setLevelAmount(BigDecimal.ZERO);
                }else{
                    goods.setShopPrice(shopPrice);
                    goods.setAgentPrice(agentPrice);
                    goods.setRegionPrice(regionPrice);
                    goods.setCoopPrice(coopPrice);
                    goods.setCouponAmount(couponAmount);
                    goods.setLevelAmount(levelAmount);
                }
            }
        }
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("goods:delete")
    public R delete(@RequestBody Integer[] ids) {
        goodsService.deleteBatch(ids);

        return R.ok();
    }

    /**
     * 查看所有列表
     */
    @RequestMapping("/queryAll")
    public R queryAll(@RequestParam Map<String, Object> params) {

        params.put("isDelete", 0);
        params.put("isSecKill", 1);
        params.put("merchantId", ShiroUtils.getUserEntity().getMerchantId());
        List<GoodsEntity> list = goodsService.queryList(params);

        return R.ok().put("list", list);
    }


    /**
     * 商品回收站
     *
     * @param params
     * @return
     */
    @RequestMapping("/historyList")
    public R historyList(@RequestParam Map<String, Object> params) {
        //查询列表数据
        SysUserEntity sysUserEntity= ShiroUtils.getUserEntity();
        Query query = new Query(params);
        query.put("merchantId",sysUserEntity.getMerchantId());
        query.put("isDelete", 1);
        List<GoodsEntity> goodsList = goodsService.queryList(query);

        int total = goodsService.queryTotal(query);

        PageUtils pageUtil = new PageUtils(goodsList, total, query.getLimit(), query.getPage());

        return R.ok().put("templates/page", pageUtil);
    }

    /**
     * 商品从回收站恢复
     */
    @RequestMapping("/back")
    @RequiresPermissions("goods:back")
    public R back(@RequestBody Integer[] ids) {
        goodsService.back(ids);

        return R.ok();
    }

    /**
     * 总计
     */
    @RequestMapping("/queryTotal")
    public R queryTotal(@RequestParam Map<String, Object> params) {

        params.put("isDelete", 0);
        int sum = goodsService.queryTotal(params);
        return R.ok().put("goodsSum", sum);
    }

    /**
     * 上架
     */
    @RequestMapping("/enSale")
    public R enSale(@RequestBody Integer id) {
        goodsService.enSale(id);

        return R.ok();
    }

    /**
     * 下架
     */
    @RequestMapping("/unSale")
    public R unSale(@RequestBody Integer id) {
        goodsService.unSale(id);

        return R.ok();
    }
}
